package name.jiaosha.air.system.controller;

import java.util.ArrayList;
import java.util.List;

import name.jiaosha.air.AppConstants;
import name.jiaosha.air.system.domain.Unit;
import name.jiaosha.air.system.service.ISystemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.ali8ba.common.PageInfo;
import com.ali8ba.common.PinyinToolkit;

@Controller
@RequestMapping("/admin/sys/")
public class UnitController {

	@Autowired
	private ISystemService systemService;

	@RequestMapping("/unitList")
	public ModelAndView getUnitList() {

		PageInfo<Unit> pageInfo = null;

		if (!AppConstants.DEBUG) {
			List<Unit> list = new ArrayList<Unit>();
			for (int i = 1; i <= 20; i++) {
				Unit unit = new Unit();
				unit.setId(i);
				unit.setName("件" + i);
				unit.setPinyin(PinyinToolkit.cn2FirstSpell(unit.getName()));
				list.add(unit);
			}

		} else {

			pageInfo = systemService.getUnitListByComId( 1,
					AppConstants.DEFAULT_SIZE);

		}

		ModelMap model = new ModelMap();
		model.addAttribute("root", pageInfo.getItemList());
		model.addAttribute("totalProperty", pageInfo.getTotalProperty());
		return new ModelAndView("jsonView", model);
	}

	@RequestMapping("/createUnit")
	public ModelAndView createUnit(@RequestParam String name) {

		if (!AppConstants.DEBUG) {

		} else {

			Unit unit = new Unit();
			unit.setName(name.trim());
			systemService.createUnit(unit);

		}

		ModelMap model = new ModelMap();
		model.addAttribute("success", "true");

		return new ModelAndView("jsonView", model);
	}

	@RequestMapping("/updateUnit")
	public ModelAndView updateUnit(@RequestParam int id,
			@RequestParam String name) {

		if (!AppConstants.DEBUG) {

		} else {

			Unit unit = systemService.getUnitById(id);

			if (unit != null) {

				unit.setName(name.trim());
				systemService.updateUnit(unit);
			}

		}

		ModelMap model = new ModelMap();
		model.addAttribute("success", "true");
		return new ModelAndView("jsonView", model);
	}

}
